package com.gjp.processdemo.config.security;

import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.IdentityService;
import org.flowable.idm.api.User;
import org.flowable.idm.engine.impl.persistence.entity.UserEntityImpl;
import org.flowable.ui.common.security.DefaultPrivileges;
import org.flowable.ui.common.security.FlowableAppUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Objects;

@Slf4j
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IdentityService identityService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = identityService.createUserQuery()
                .userLastName(username)
                .singleResult();
        //判断当前用户是否存在
        if (Objects.isNull(user)) {
            //测试代码，直接返回Null了
            return null;
        }
        //构造用户对象 如果对接自己业务系统的用户表，可以转换一下对象塞进去就行
        FlowableAppUser flowableAppUser = new FlowableAppUser(
                user,
                user.getLastName(),
                AuthorityUtils.commaSeparatedStringToAuthorityList(
                        String.join(",",
                        Arrays.asList(
                                DefaultPrivileges.ACCESS_MODELER,
                                DefaultPrivileges.ACCESS_IDM,
                                DefaultPrivileges.ACCESS_ADMIN,
                                DefaultPrivileges.ACCESS_TASK,
                                DefaultPrivileges.ACCESS_REST_API)))
        );
//        org.springframework.security.core.userdetails.User userDetails = new org.springframework.security.core.userdetails.User(
//                user.getLastName()
//                , user.getPassword()
//                , AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",", Arrays.asList("")))
//        );
        return flowableAppUser;
    }
}
